<?php
/**
 * Created by PhpStorm.
 * User: Dave
 * Date: 2018/5/10
 * Time: 10:59
 */

namespace Biz\tools;

use Doraemon\pockets\config\IniConfig;
use Doraemon\tools\HhzClient;
use GuzzleHttp\Psr7\Uri;

class BizUrl
{
    const _CONFIG_FILE_ = "share";
    const _CONFIG_SELECT_ = "biz";

    const ENV_TYPE_APP_URL_PARAMS = 'in_app';
    const ENV_TYPE_MINIPOROGRAM_URL_PARAMS = 'in_mp';

    const SCHEME_APP = 'hhz';
    const SCHEME_APP_BASE64 = 'hhzb';
    const SCHEME_APP_URL_BASE64 = 'hhz://urlb:';
    const SCHEME_HTTP = 'http';
    const SCHEME_HTTPS = 'https';
    const SCHEME_MINIPROGRAM = 'mp';

    const APP_PACKAGE_JD = 'com.jingdong.app.mall';//京东app
    const APP_PACKAGE_TAOBAO = 'com.taobao.taobao';//淘宝app
    const APP_PACKAGE_WECHAT_MINIPROGRAM = 'com.tencent.mm';//微信小程序

    static private $base_url = null;

    static public function getDomain()
    {
        if (is_null(self::$base_url)) {
            $config = IniConfig::getConfigSelect(static::_CONFIG_FILE_, static::_CONFIG_SELECT_);
            self::$base_url = $config['share_url'];
        }
        return self::$base_url;
    }

    static function formatUrlByClientType($url)
    {
        if ($url) {
            try {
                $urlMaker = new Uri($url);
                $urlMaker = Uri::withoutQueryValue($urlMaker, self::ENV_TYPE_APP_URL_PARAMS);
                $urlMaker = Uri::withoutQueryValue($urlMaker, self::ENV_TYPE_MINIPOROGRAM_URL_PARAMS);
                $clientType = HhzClient::getClientType();
                switch ($urlMaker->getScheme()) {
                    case self::SCHEME_HTTP:
                    case self::SCHEME_HTTPS:
                        switch ($clientType) {
                            case HhzClient::APPTYPE_IOS:
                            case HhzClient::APPTYPE_ANDROID:
                                $urlMaker = Uri::withQueryValue($urlMaker, self::ENV_TYPE_APP_URL_PARAMS, 1);
                                $urlMaker = BizUrl::SCHEME_APP_URL_BASE64 . base64_encode((string)$urlMaker);
                                break;
                            case HhzClient::APPTYPE_MINIPROGRAM:
                            case HhzClient::APPTYPE_TUAN_MINIPROGRAM:
                            case HhzClient::APPTYPE_PARAGRAPH_MINIPROGRAM:
                                $urlMaker = Uri::withQueryValue($urlMaker, self::ENV_TYPE_MINIPOROGRAM_URL_PARAMS, 1);
                                break;
                            default:
                                break;
                        }
                        break;
                    case self::SCHEME_MINIPROGRAM:
                        switch ($clientType) {
                            case HhzClient::APPTYPE_IOS:
                            case HhzClient::APPTYPE_ANDROID:
                                $urlMaker = "";
                                break;
                            case HhzClient::APPTYPE_MINIPROGRAM:
                            case HhzClient::APPTYPE_TUAN_MINIPROGRAM:
                            case HhzClient::APPTYPE_PARAGRAPH_MINIPROGRAM:
                                break;
                            default:
                                $urlMaker = "";
                                break;
                        }
                        break;
                    case self::SCHEME_APP:
                    case self::SCHEME_APP_BASE64:
                        switch ($clientType) {
                            case HhzClient::APPTYPE_IOS:
                            case HhzClient::APPTYPE_ANDROID:
                                return $url;
                                break;
                            case HhzClient::APPTYPE_MINIPROGRAM:
                            case HhzClient::APPTYPE_TUAN_MINIPROGRAM:
                            case HhzClient::APPTYPE_PARAGRAPH_MINIPROGRAM:
                            default:
                                $urlMaker = "";
                                break;
                        }
                        break;
                }
                return (string)$urlMaker;
            } catch (\Exception $e) {
                return $url;
            }
        } else {
            return "";
        }
    }


    static function getAppUrlParams($url, $appType = "")
    {
        switch ($appType) {
            case self::ENV_TYPE_APP_URL_PARAMS:
                $url .= '&' . self::ENV_TYPE_APP_URL_PARAMS . '=1';
                break;
            case self::ENV_TYPE_MINIPOROGRAM_URL_PARAMS:
                $url .= '&' . self::ENV_TYPE_MINIPOROGRAM_URL_PARAMS . '=1';
                break;
            default:
                break;
        }
        return $url;
    }

    public static function h5SpecialInfo($specialId)
    {
        return self::getDomain() . '/h5_thematic?special_id=' . $specialId;
    }

    /**
     * @param $specialId 活动id
     * @param string $inApp 1:站内 2:站外
     * @return string 活动url
     */
    public static function h5ShopActivity($specialId, $inApp = '')
    {
        $url = self::getDomain() . '/h5_shopActivity?special_id=' . $specialId;
        $url = $inApp ? ($url . '&in_app=' . $inApp) : $url;
        return $url;
    }

    public static function h5ActivityPage($pageId, $appType = '')
    {
        $url = self::getDomain() . '/h5_activityPage?page_id=' . $pageId;
        $url = self::getAppUrlParams($url, $appType);
        return $url;
    }


    public static function h5GoodsInfo($goodsID)
    {
        return self::getDomain() . '/shop/allowance?goods_id=' . $goodsID . "&";
    }

    public static function h5GoodsPintuan($teamId, $isPre = true)
    {
        if ($isPre) {
            return self::getDomain() . '/shop/groupBuy/groupBuyDetail?team_id=' . $teamId;
        } else {
            return '/shop/groupBuy/groupBuyDetail?team_id=' . $teamId;
        }
    }

    public static function h5OrderRefundInfo($refundOrId, $base64 = true)
    {
        $url = self::getDomain() . '/h5_refundDetail?refund_order_no=' . $refundOrId;
        if ($base64) {
            return base64_encode($url);
        } else {
            return $url;
        }
    }

    public static function h5MealInfo($mealId, $base64 = false)
    {
        $url = self::getDomain() . '/h5_buildingshare?meal_id=' . $mealId;
        if ($base64) {
            return base64_encode($url);
        } else {
            return $url;
        }
    }

    public static function h5MealListInfo($goodsId, $base64 = true)
    {
        $url = self::getDomain() . '/h5_package?goods_id=' . $goodsId;
        if ($base64) {
            return base64_encode($url);
        } else {
            return $url;
        }
    }

    public static function h5MealDetail($mealId, $base64 = false)
    {
        $url = self::getDomain() . '/h5_graphic?meal_id=' . $mealId;

        if ($base64) {
            return base64_encode($url);
        } else {
            return $url;
        }
    }

    public static function h5GoodsDetail($goodsId, $base64 = true)
    {
        $url = self::getDomain() . '/static_page/graphic_details?goods_id=' . $goodsId;
        return $url;
    }

    public static function h5Lottery()
    {
        $url = self::getDomain() . '/h5_lottery';
        return $url;
    }
    /**
     * 已过时
     * @param $wikiId
     * @return string
     * @deprecated
     */
    public static function h5WikiInfo($wikiId)
    {
        return self::getDomain() . '/shop/goods-detail/wiki?goods_id=' . $wikiId . "&";
    }

    public static function storeHome($store_uid)
    {
        return '/pages/home/index?uid=' . $store_uid;
    }

    /**
     * 获取京东商品详情url
     * @param $skuId
     * @param string $productUrl
     * @return array
     */
    public static function getJdProductDetailUrl($skuId, $productUrl = '')
    {
        $params = [
            "category" => "jump",
            "des" => "productDetail",
            "skuId" => (string)$skuId,
            "sourceType" => "JSHOP_SOURCE_TYPE",
            "sourceValue" => "JSHOP_SOURCE_VALUE"
        ];
        $url = $productUrl ? $productUrl : RealUrl::formatLink($skuId, RealUrl::URL_TYPE_JD);
        return self::getJdUrl($params, $url);
    }

    /**
     * 获取京东店铺url
     * @param $shopId
     * @param string $shopUrl
     * @return array
     */
    public static function getJdShopUrl($shopId, $shopUrl = '')
    {
        $params = [
            "category" => "jump",
            "des" => "jshopMain",
            "shopId" => (string)$shopId,
            "sourceType" => "M_sourceFrom",
            "sourceValue" => "dp"
        ];
        $url = $shopUrl ? $shopUrl : RealUrl::getJDShopUrl($shopId);
        return self::getJdUrl($params, $url);
    }

    /**
     * 获取京东领取优惠券url
     * @param $couponUrl
     * @return array
     */
    public static function getJdCouponUrl($couponUrl)
    {
        $params = [
            "category" => "jump",
            "des" => "getCoupon",
            "url" => $couponUrl,
            "sourceType" => "JSHOP_SOURCE_TYPE",
            "sourceValue" => "JSHOP_SOURCE_VALUE"
        ];
        $url = $couponUrl;
        return self::getJdUrl($params, $url);
    }

    /**
     * 获取京东通用链接（商品详情）
     * @param $url
     * @return array|string[]
     */
    public static function getJdMUrl($url)
    {
        $params = [
            "category" => "jump",
            "des" => "m",
            "url" => $url,
            "sourceType" => "JSHOP_SOURCE_TYPE",
            "sourceValue" => "JSHOP_SOURCE_VALUE",
            "M_sourceFrom" => "h5auto",
            "msf_type" => "auto"
        ];
        return self::getJdUrl($params, $url);
    }

    /**
     * 获取京东链接
     * @param array $params openApp.jdMobile 必须参数
     * @param string $url h5原始链接
     * @return array
     */
    public static function getJdUrl(array $params, string $url)
    {
        $result = [
            'h5_link' => '',
            'open_app_link' => '',
        ];
        if ($params && $url) {
            $jdOpenAppLink = trim("openApp.jdMobile://virtual?params=" . json_encode($params));
            $package = self::APP_PACKAGE_JD;
            $openAppLink = self::getOpenAppLink($jdOpenAppLink, $package, $url);
            $result = [
                'h5_link' => $url,
                'open_app_link' => $openAppLink,
            ];
        }
        return $result;
    }

    /**
     * 获取淘宝url
     * @param $url h5链接
     * @return array
     */
    public static function getTbUrl($url)
    {
        $url = trim($url);
        $parseArr = parse_url($url);
        $tbOpenAppLink = 'taobao://' . $parseArr['host'];
        if (isset($parseArr['path'])) {
            $tbOpenAppLink .= $parseArr['path'];
            if (isset($parseArr['query'])) {
                $tbOpenAppLink .= '?' . $parseArr['query'];
            }
        }
        $package = self::APP_PACKAGE_TAOBAO;
        $openAppLink = self::getOpenAppLink($tbOpenAppLink, $package, $url);
        return [
            'h5_link' => $url,
            'open_app_link' => $openAppLink,
        ];
    }

    /**
     * 获取好好住打开第三方app的内链
     * @param $otherAppLink 打开第三方app链接
     * @param $package 第三方app package
     * @param $url h5链接
     */
    public static function getOpenAppLink($otherAppLink, $package, $url)
    {
        $fallback = $url ? 'niceliving://webview/normalscreen?protego=' . urlencode(base64_encode(json_encode(['url' => $url]))) : '';
        $openAppLink = 'niceliving://open/app?protego=' . urlencode(base64_encode(json_encode(['link' => $otherAppLink, 'package' => $package, 'fallback' => $fallback])));
        return $openAppLink;
    }
}
